package org.grow.yc.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: xwg
 * @CreateDate: 2024/9/27
 */

@RequestMapping("/upload")
@RestController
public class UploadController {
    @Value("${my-upload}")
    private String uploadDir;

    //    consumes = ["multipart/form-data"]
//    图片的上传与回显
    @PostMapping(value = "/one",consumes = "multipart/form-data")
    public String uploadOne(@RequestParam("file") MultipartFile file) throws IOException {
        long l = System.currentTimeMillis();
//        取 [1000 , 9999)之间的随机数
        Integer i =  ThreadLocalRandom.current().nextInt(8999)+1000;
//        165222255T2555
        String target = l+"T"+i;
        System.out.println("target name : "+target);
        String o = file.getOriginalFilename();
        String ext = o.substring(o.lastIndexOf('.'));
        String finalName = target+ext;
        System.out.println(finalName);
        file.transferTo(Paths.get(uploadDir,finalName));
        return finalName;
    }
    @PostMapping(value = "/many")
    public List<String> uploadOne(@RequestParam("file") MultipartFile[] file) throws IOException {
        ArrayList<String> results = new ArrayList<>();
        for (MultipartFile f : file) {
            long l = System.currentTimeMillis();
//        取 [1000 , 9999)之间的随机数
            Integer i =  ThreadLocalRandom.current().nextInt(8999)+1000;
//        165222255T2555
            String target = l+"T"+i;
            System.out.println("target name : "+target);
            String o = f.getOriginalFilename();
            String ext = o.substring(o.lastIndexOf('.'));
            String finalName = target+ext;
            System.out.println(finalName);
            f.transferTo(Paths.get(uploadDir,finalName));
            results.add(finalName);
        }
        return results;
    }
}
